package com.qianli.cashmama.trade.openApi.job;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.fqgj.common.api.Response;
import com.fqgj.common.utils.DateUtil;
import com.fqgj.common.utils.HttpUtil;
import com.fqgj.common.utils.StringUtils;
import com.fqgj.xjd.user.client.UserContactService;
import com.fqgj.xjd.user.client.UserInfoService;
import com.fqgj.xjd.user.client.enums.UserContactFamilyTypeEnum;
import com.fqgj.xjd.user.client.enums.UserEducationEnum;
import com.fqgj.xjd.user.client.enums.UserLanguageEnum;
import com.fqgj.xjd.user.client.response.*;
import com.qianli.cashmama.product.facade.AppFacade;
import com.qianli.cashmama.product.facade.result.AppPackageInfo;
import com.qianli.cashmama.trade.common.dto.UserTradeSnapshotDto;
import com.qianli.cashmama.trade.dao.TTradeExtraDao;
import com.qianli.cashmama.trade.domain.model.BillBase;
import com.qianli.cashmama.trade.domain.model.TimeoutEvent;
import com.qianli.cashmama.trade.domain.model.TradeBase;
import com.qianli.cashmama.trade.entity.TTradeExtraEntity;
import com.qianli.cashmama.trade.integration.product.ProductIntegrationService;
import com.qianli.cashmama.trade.integration.product.dto.ProductDto;
import com.qianli.cashmama.trade.integration.user.UserIntegrationService;
import com.qianli.cashmama.trade.integration.user.dto.UserBaseInfoDto;
import com.qianli.cashmama.trade.openApi.job.service.CollectionIntegrationService;
import com.qianli.cashmama.trade.openApi.job.vo.*;
import com.qianli.cashmama.trade.repo.BillBaseRepository;
import com.qianli.cashmama.trade.repo.TradeBaseRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * 推送逾期账单给催收系统
 * Created with IntelliJ IDEA.
 * User: sm
 * Date: 2017/7/24
 * Time: 下午3:08
 */
@Component
public class PushBillToOverdue {

    private static final Logger LOGGER = LoggerFactory.getLogger(PushBillToOverdue.class);

    @Autowired
    private CollectionIntegrationService collectionIntegrationService;

    @Autowired
    private TradeBaseRepository tradeBaseRepository;

    @Autowired
    private BillBaseRepository billBaseRepository;

    @Autowired
    private UserIntegrationService userIntegrationService;

    @Autowired
    private ProductIntegrationService productIntegrationService;

    @Autowired
    private AppFacade appFacade;

    @Autowired
    private TTradeExtraDao tTradeExtraDao;

    @Autowired
    private UserInfoService userInfoService;

    @Autowired
    private UserContactService userContactService;

    public boolean pushToCollection(String billNo) {
        try {
            LOGGER.info("== 推送给催收 ==,billNo:{}", billNo);
            BillBase billBase = billBaseRepository.getBillByBillNo(billNo);
            if (billBase == null) {
                return false;
            }

            TradeBase tradeBase = tradeBaseRepository.load(billBase.getTradeNo());
            if (tradeBase == null) {
                LOGGER.info("== 交易不存在 不推送 ==,billNo:{}", billNo);
                return false;
            }

            if (billBase.getPaidStatus().equals(com.qianli.cashmama.trade.common.enums.BillPaidStatusEnum.CLEAR_REPAYMENT)) {
                LOGGER.info("== 账单已还清,不推送给催收 ==,billNo:{}", billNo);
                return true;
            }

            ProductDto productInfoByCode = productIntegrationService.getProductInfoByCode(tradeBase.getProductCode());
            tradeBase.setBorrowRatio(productInfoByCode.getBorrowRatio());

            UserBaseInfoDto userBaseInfoDto = userIntegrationService.getUserBaseInfoByUserCode(tradeBase.getUserCode(), tradeBase.getProductCategory());
            UserTradeSnapshotDto userTradeSnapshotDto = userIntegrationService.getUserTradeSnapshotInfoByUserCode(tradeBase.getUserCode(), tradeBase.getProductCategory());
//            UserAuthEmail userAuthEmail = userIntegrationService.getUserEmail(tradeBase.getUserCode());

            //组装订单信息
            ClOrderInputVo clOrderInputVo = new ClOrderInputVo();
            clOrderInputVo.setBorrowCapital(billBase.getBorrowCapital().toPlainString());
            clOrderInputVo.setReceivedCapital(billBase.getReceivedCapital().toPlainString());
            clOrderInputVo.setPaidAmount(billBase.getPaidCapital().subtract(billBase.getDiscountCapital()).toPlainString());
            clOrderInputVo.setDeductAmount(billBase.getDiscountCapital().toPlainString());
            clOrderInputVo.setInterest(billBase.getInterestFee().toPlainString());
            clOrderInputVo.setServiceFee(billBase.getBorrowServiceFee().toPlainString());
            clOrderInputVo.setLateServiceFee(tradeBase.getOverdueServiceFee().toPlainString());
            clOrderInputVo.setLateFeeRatio(tradeBase.getOverdueRatio().toPlainString());
            clOrderInputVo.setChannel(tradeBase.getChannelCode());
            clOrderInputVo.setReceivedDate(DateUtil.getDate(tradeBase.getReceivedDate(), "yyyy-MM-dd HH:mm:ss"));
            clOrderInputVo.setRepaymentDate(DateUtil.getDate(billBase.getRepaymentDate(), "yyyy-MM-dd HH:mm:ss"));
            clOrderInputVo.setBorrowType(tradeBase.isNewUser() ? 1 : 2);
            clOrderInputVo.setCapitalCode(tradeBase.getCapitalCode() + "");
            clOrderInputVo.setExtensionNumber(billBase.getExtensionCount());

            //组装用户信息
            ClUserInfoInputVo clUserInfoInputVo = new ClUserInfoInputVo();
            clUserInfoInputVo.setName(userBaseInfoDto.getUserName());
            clUserInfoInputVo.setMobile(userBaseInfoDto.getMobile());
            clUserInfoInputVo.setKycNo(userBaseInfoDto.getIdentityNo());
            clUserInfoInputVo.setEmail("");

            UserInfo userInfo = userInfoService.getUserInfoByUserCode(tradeBase.getUserCode()).getData();
            clUserInfoInputVo.setUserLanguage(UserLanguageEnum.getEnumByType(userBaseInfoDto.getUserLanguage()) == null ?
                    null : UserLanguageEnum.getEnumByType(userBaseInfoDto.getUserLanguage()).getDesc());
            clUserInfoInputVo.setState(userInfo.getUserResident().getProvince());
            clUserInfoInputVo.setCity(userBaseInfoDto.getCity());
            clUserInfoInputVo.setAddress(userInfo.getUserResident().getAddress());

            Integer sex = 1;
            if (userBaseInfoDto.getGender() == 1) {
                sex = 1;
            } else if (userBaseInfoDto.getGender() == 2) {
                sex = 0;
            } else if (userBaseInfoDto.getGender() == 3) {
                sex = 2;
            }
            clUserInfoInputVo.setSex(sex);
            clUserInfoInputVo.setBirthday(userBaseInfoDto.getBirthday());
            clUserInfoInputVo.setPanCardNo(userTradeSnapshotDto.getUserPanInfo().getCardNo());
            clUserInfoInputVo.setAadhaarNo(userTradeSnapshotDto.getUserKycDocumentInfo().getCardId());
            UserEducationEnum userEducationEnum = UserEducationEnum.getEnumByType(userInfo.getUserBase().getEducation());
            clUserInfoInputVo.setEducation(userEducationEnum == null ? UserEducationEnum.BELOW_HIGH_SCHOOL.getType() : userEducationEnum.getType());
            clUserInfoInputVo.setMarriedStatus(userInfo.getUserBase().getMarriedStatus());
            UserFamilyContact userFamilyContact = userTradeSnapshotDto.getUserSocialContact().getUserEmergencyContact().getUserFamilyContact();
            clUserInfoInputVo.setContact1Name(StringUtils.isNotEmpty(userFamilyContact.getContactName()) ? userFamilyContact.getContactName() : userFamilyContact.getName());
            clUserInfoInputVo.setContact1Mobile(userFamilyContact.getMobile());

            Integer contact1Relative = 6;
            UserContactFamilyTypeEnum userContactFamilyTypeEnum = userTradeSnapshotDto.getUserSocialContact().getUserEmergencyContact().getUserFamilyContact().getUserContactFamilyTypeEnum();
            if (UserContactFamilyTypeEnum.MOTHER.equals(userContactFamilyTypeEnum) || UserContactFamilyTypeEnum.FATHER.equals(userContactFamilyTypeEnum)) {
                contact1Relative = 1;
            } else if (UserContactFamilyTypeEnum.Brother.equals(userContactFamilyTypeEnum)) {
                contact1Relative = 2;
            } else if (UserContactFamilyTypeEnum.SISTERS.equals(userContactFamilyTypeEnum)) {
                contact1Relative = 3;
            } else if (UserContactFamilyTypeEnum.Spouse_OR_Partner.equals(userContactFamilyTypeEnum)) {
                contact1Relative = 5;
            } else {
                contact1Relative = 6;
            }

            clUserInfoInputVo.setContact1Relative(contact1Relative);

            UserFriendContact userFriendContact = userTradeSnapshotDto.getUserSocialContact().getUserEmergencyContact().getUserFriendContact();
            clUserInfoInputVo.setContact2Name(StringUtils.isNotEmpty(userFriendContact.getContactName()) ? userFriendContact.getContactName() : userFriendContact.getName());
            clUserInfoInputVo.setContact2Mobile(userFriendContact.getMobile());
            clUserInfoInputVo.setContact2Relative(6);
            clUserInfoInputVo.setPinCode(userInfo.getUserResident().getPinCode());

            //组装基础信息
            ClOrderReceiveRequest request = new ClOrderReceiveRequest();
            request.setToken("1989919");
            request.setTradeNo(tradeBase.getTradeNo());
            request.setOrderBillNo(billBase.getBillNo());
            request.setUserCode(tradeBase.getUserCode());
            String appName =  tradeBase.getProductCategory();
            request.setAppName(appName);
            request.setProductType(tradeBase.getProductCategory());
            request.setProductCode(tradeBase.getProductCode());

            request.setUserInfo(clUserInfoInputVo);
            request.setOrderInfo(clOrderInputVo);

            boolean pushSuccess = collectionIntegrationService.pushToCollection(request);

            if (pushSuccess) {
                //开始推送通讯录给催收
                List<ClContactsInputVo> clContactsInputVoList2 = new ArrayList<>();
                try {

                    Response<List<UserContactAddressBook>> response = userContactService.getUserDeviceContactListByUserCode(tradeBase.getUserCode());
                    List<UserContactAddressBook> userContactAddressBookList = response.getData();
                    List<String> contactUrlList = Stream.of(userContactAddressBookList.stream().map(UserContactAddressBook::getContactUrl).collect(Collectors.toList()))
                            .flatMap(Collection::stream).filter(item -> item.contains("http")).distinct().collect(Collectors.toList());

                    LOGGER.info("加载通讯录,tradeNo:{},contactUrlList:{}", tradeBase.getTradeNo(), contactUrlList.toString());

                    List<ClContactsInputVo> clContactsInputVoList = new ArrayList<>();
                    for (int i = contactUrlList.size() - 1; i >= 0; i--) {
                        String url = contactUrlList.get(i);
                        String contentStr = HttpUtil.getPage(url);
                        if (StringUtils.isEmpty(contentStr)) {
                            continue;
                        }
                        try {
                            JSONObject j1 = JSON.parseObject(contentStr);
                            JSONArray contactsJA = j1.getJSONArray("contacts");
                            for (int k = 0; k < contactsJA.size(); k++) {
                                JSONObject item = contactsJA.getJSONObject(k);
                                ClContactsInputVo vo = new ClContactsInputVo();
                                vo.setName(item.getString("name"));
                                vo.setMobile(IndiaMobileUtil.countryCodeFilter(item.getString("phone")));
                                clContactsInputVoList.add(vo);
                            }
                        } catch (Exception e) {
                            LOGGER.warn("获取通讯录对象失败,tradeNo:{},url:{}", tradeBase.getTradeNo(), url);
                        }
                    }
                    for (ClContactsInputVo vo : clContactsInputVoList) {
                        boolean has = false;
                        for (ClContactsInputVo vo1 : clContactsInputVoList2) {
                            if (vo1.getMobile().equalsIgnoreCase(vo.getMobile())) {
                                has = true;
                                break;
                            }
                        }
                        if (!has) {
                            clContactsInputVoList2.add(vo);
                        }
                    }
                } catch (Exception e) {
                    LOGGER.warn("解析通讯录失败,tradeNo:{}", tradeBase.getTradeNo(), e);
                }

                ClOrderContactsRequest clOrderContactsRequest = new ClOrderContactsRequest();
                clOrderContactsRequest.setToken("1989919");
                clOrderContactsRequest.setUserCode(tradeBase.getUserCode());
                clOrderContactsRequest.setTradeNo(tradeBase.getTradeNo());
                clOrderContactsRequest.setContacts(clContactsInputVoList2);
//                clOrderContactsRequest.setSmsList(clSmsInputVoList);

                boolean pushContacts = collectionIntegrationService.pushContactsToCollection(clOrderContactsRequest);
                LOGGER.info("通讯录推送结果,tradeNo:{},{}", tradeBase.getTradeNo(), pushContacts);
            }

            return pushSuccess;
        } catch (Exception e) {
            LOGGER.error("推送给催收失败," + billNo, e);
            return false;
        }
    }

    /**
     * 查询用户下单app包信息
     *
     * @param userCode
     * @param tradeNo
     * @param defaultValue
     * @return
     */
    public String getAppPackageInfoByUserCode(String userCode, String tradeNo, String defaultValue) {
        try {
            String packageName = null;
            if (StringUtils.isEmpty(tradeNo)) {
                UserAccessInfo userAccessInfo = userIntegrationService.getUserAccessInfoByUserCode(userCode);
                packageName = userAccessInfo.getPackageName();
            } else {
                TTradeExtraEntity tTradeExtraEntity = tTradeExtraDao.selectByTradeNo(tradeNo);
                if (tTradeExtraEntity != null && StringUtils.isNotEmpty(tTradeExtraEntity.getPackageName())) {
                    packageName = tTradeExtraEntity.getPackageName();
                } else {
                    UserAccessInfo userAccessInfo = userIntegrationService.getUserAccessInfoByUserCode(userCode);
                    packageName = userAccessInfo.getPackageName();
                }
            }
            AppPackageInfo appPackageInfo = appFacade.getAppPackageInfoByPackageName(packageName).getData();
            LOGGER.info("调试日志1,userCode:{},tradeNo:{},packageName:{},appPackageInfo:{}", userCode, tradeNo, packageName, JSON.toJSONString(appPackageInfo));
            return appPackageInfo.getAppName();
        } catch (Exception e) {
            LOGGER.error("查询失败,userCode:{}", userCode, e);
            return defaultValue;
        }
    }
}
